package com.yuanqiworld.vw.web;

import com.yuanqiworld.vw.domain.UserInfo;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.validation.Valid;

@RequestMapping("/tokens")
@Controller
public class TokenController {


    // 修改自己的密码.
    @RequestMapping(params = "passwordForm", produces = "text/html")
    public String updatePasswordForm(Model uiModel) {
        User me = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        UserInfo userInfo = UserInfo.findUserInfoesByUsername(me.getUsername()).getSingleResult();
        uiModel.addAttribute("userInfo", userInfo);
        return "tokens/updatePassword";
    }

    // 提交修改自己密码.
    @RequestMapping(method = RequestMethod.PUT, params = "updatePassword", produces = "text/html")
    public String updatePassword(UserInfo userInfo, BindingResult bindingResult, Model uiModel) {

        User me = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        UserInfo user = UserInfo.findUserInfoesByUsername(me.getUsername()).getSingleResult();

        if (!UserInfo.isPasswordValid(user.getPassword(), userInfo.getOldPassword())) {
            bindingResult.rejectValue("oldPassword", "error.oldpassword");
        }

        if (userInfo.getPassword() != null) {
            if (!userInfo.getPassword().equals(userInfo.getConfirmPassword())) {
                bindingResult.rejectValue("confirmPassword", "error.confirmpassword");
            }
        }

        if (bindingResult.hasErrors()) {
            uiModel.addAttribute("userInfo", userInfo);
            return "tokens/updatePassword";
        }

        user.setPassword(userInfo.getPassword());
        user.encodePassword();
        user = user.merge();

        uiModel.addAttribute("userInfo", user);
        return "tokens/updatePasswordSuccess";
    }

}
